class MyModel {
  /**
   * 上传图片/文件
   */
  uploadFile(page, path, type) {
    let filePath = "";
    let fileName = "";
    // 0-图片；1-文件；
    let params = {
      'type': type
    };
    // 上传图片
    if (type == 0) {
      filePath = path[0];
    } else if (type == 1) {
      filePath = path[0].path;
      fileName = path[0].name;
      params.fileName = fileName;
    }
    wx.showToast({
        icon: "loading",
        title: "正在上传文件"
    }),
    wx.uploadFile({
        url: api_base_url + "/uploadFile",
        filePath: filePath,
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: params,
        success: function (res) {
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '文件或图片上传失败',
              showCancel: false
            });
            return;
          }
          let receivedata = JSON.parse(res.data);
          if (receivedata.data.state == "fail") {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
          if (type == 0) {
            page.setData({
              //上传成功修改显示图片(filePath 是临时生成用于显示的图片，imagePath 是后端存储的相对路径)
              photo: filePath,
              imagePath: receivedata.data.filePath
            })
          } else if (type == 1) {
            let fileName = receivedata.data.fileName;
            // 文件名称截取
            if (fileName) {
              if (fileName.length > 15) {
                fileName = fileName.substr(0, 15) + "...";
              }
            }
            page.setData({
              //上传成功修改文件名显示
              attachment: fileName
            })
          }
        },
        fail: function (e) {
          wx.showModal({
            title: '提示',
            content: '文件上传失败',
            showCancel: false
          })
        },
        complete: function () {
          wx.hideToast();
        }
      })
  }
}

export {
  MyModel
}
